package com.mmd.manage.web;

import com.mmd.bean.CODE;
import com.mmd.bean.WebJsonBean;
import com.mmd.common.enums.YesNoEnums;
import com.mmd.exception.GameException;
import com.mmd.manage.service.BillService;
import com.mmd.manage.vo.AddAmountEo;
import com.mmd.manage.vo.ExportYsYfVo;
import com.mmd.manage.vo.QueryBillListEo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 账单
 */
@RequestMapping(value = "/api/bill")
@Controller
public class BillController {

    @Autowired
    private BillService billService;


    /**
     * 充值
     *
     * @return
     */
    @RequestMapping(value = "/addAmount")
    @ResponseBody
    public WebJsonBean addAmount(AddAmountEo eo) {
        return new WebJsonBean(CODE.SUCCESS, billService.addAmount(eo));
    }


    /**
     * 查询用户下拉
     *
     * @return
     */
    @RequestMapping(value = "/userList")
    @ResponseBody
    public WebJsonBean userList() {
        return new WebJsonBean(CODE.SUCCESS, billService.userList());
    }


    /**
     * 查询列表
     *
     * @return
     */
    @RequestMapping(value = "/getUserBillList")
    @ResponseBody
    public WebJsonBean getUserBillList(QueryBillListEo eo) {
        return new WebJsonBean(CODE.SUCCESS, billService.getUserBillList(eo));
    }

    /**
     * 查询供应商账单列表
     *
     * @return
     */
    @RequestMapping(value = "/getSupBillList")
    @ResponseBody
    public WebJsonBean getSupBillList(QueryBillListEo eo) {
        return new WebJsonBean(CODE.SUCCESS, billService.getSupBillList(eo));
    }

    /**
     * 查询用户端的用户账单
     *
     * @return
     */
    @RequestMapping(value = "/getUserBills")
    @ResponseBody
    public WebJsonBean getUserBills(QueryBillListEo eo) {
        return new WebJsonBean(CODE.SUCCESS, billService.getUserBills(eo));
    }

    /**
     * 供应商端的财务管理
     * 是对admin进行收款的
     *
     * @return
     */
    @RequestMapping(value = "/getAdminBills")
    @ResponseBody
    public WebJsonBean getAdminBills(QueryBillListEo eo) {
        return new WebJsonBean(CODE.SUCCESS, billService.getAdminBills(eo));
    }

    @RequestMapping(value = "export")
    @ApiOperation("导出订单列表")
    public WebJsonBean exportOrderList(String startTime, String endTime, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(startTime)){
            throw new GameException(new CODE(9999,"请选择开始时间"));
        }
        if (StringUtils.isEmpty(endTime)){
            throw new GameException(new CODE(9999,"请选择结束时间"));
        }

        HSSFWorkbook wb = new HSSFWorkbook();
        // sheet 对应一个工作页
        Sheet sheet = wb.createSheet("应收应付");
        // 创建第一行为标题行
        Row hssfRow = sheet.createRow(0);
        Cell hssfCell = hssfRow.createCell(0);
        String[] titleArr = {"序号", "业务日期", "客户", "原单号", "转单号", "目的地", "渠道",
                "件数", "计费重量", "商品类型", "单价", "附加费", "单独报关/操作费", "费用", "备注",
                "计费重量", "单价", "附加费", "单独报关/操作费", "成本", "运输费用", "毛利"};
        int i = 0;
        /* for循环生成列名 */
        for (String key : titleArr) {
            hssfCell = hssfRow.createCell(i);
            hssfCell.setCellValue(key);
            i++;
        }

        List<ExportYsYfVo> list = billService.getExportYsYfVoList(startTime, endTime);

        // 填充数据
        int rowIndex = 0;
        for (int j = 1; j <= list.size(); j++) {
            ExportYsYfVo vo = list.get(j - 1);
            rowIndex++;
            hssfRow = sheet.createRow(rowIndex);
            //序号
            hssfCell = hssfRow.createCell(0);
            hssfCell.setCellValue(rowIndex);
            //业务日期
            hssfCell = hssfRow.createCell(1);
            hssfCell.setCellValue(vo.getBusinessDate());
            //客户
            hssfCell = hssfRow.createCell(2);
            hssfCell.setCellValue(vo.getCustomer());
            //原单号
            hssfCell = hssfRow.createCell(3);
            hssfCell.setCellValue(vo.getOrderNo());
            //转单号
            hssfCell = hssfRow.createCell(4);
            hssfCell.setCellValue(vo.getTrackingNo());
            //目的地
            hssfCell = hssfRow.createCell(5);
            hssfCell.setCellValue(vo.getDestinationCountry());
            //渠道
            hssfCell = hssfRow.createCell(6);
            hssfCell.setCellValue(vo.getChannel());
            //件数
            hssfCell = hssfRow.createCell(7);
            hssfCell.setCellValue(vo.getNumber());
            //计费重量
            hssfCell = hssfRow.createCell(8);
            hssfCell.setCellValue(vo.getWeightSum());
            //商品类型
            hssfCell = hssfRow.createCell(9);
            hssfCell.setCellValue(vo.getProductTypeName());
            //单价
            hssfCell = hssfRow.createCell(10);
            hssfCell.setCellValue(vo.getSinglePrice().toString());
            //附加费
            hssfCell = hssfRow.createCell(11);
            hssfCell.setCellValue(vo.getAttachFee().toString());
            //单独报关/操作费
            hssfCell = hssfRow.createCell(12);
            hssfCell.setCellValue(vo.getSingleDeclareOrOperatFee().toString());
            //费用
            hssfCell = hssfRow.createCell(13);
            hssfCell.setCellValue(vo.getTotalFee().toString());
            //备注
            hssfCell = hssfRow.createCell(14);
            hssfCell.setCellValue(vo.getRemark());

            boolean isChooseSup = vo.getChooseSup() == YesNoEnums.YES.getCode() ? true : false;

            //计费重量
            hssfCell = hssfRow.createCell(15);
            hssfCell.setCellValue(isChooseSup?vo.getSu_weightSum():"");
            //单价
            hssfCell = hssfRow.createCell(16);
            hssfCell.setCellValue(isChooseSup?vo.getSu_singlePrice()==null?"":vo.getSu_singlePrice().toString():"");
            //附加费
            hssfCell = hssfRow.createCell(17);
            hssfCell.setCellValue(isChooseSup?vo.getSu_attachFee()==null?"":vo.getSu_attachFee().toString():"");
            //单独报关/操作费
            hssfCell = hssfRow.createCell(18);
            hssfCell.setCellValue(isChooseSup?vo.getSu_singleDeclareOrOperatFee()==null?"":vo.getSu_singleDeclareOrOperatFee().toString():"");
            //成本
            hssfCell = hssfRow.createCell(19);
            hssfCell.setCellValue(isChooseSup?vo.getSu_cost()==null?"":vo.getSu_cost().toString():"");
            //运输费用
            hssfCell = hssfRow.createCell(20);
            hssfCell.setCellValue(isChooseSup?vo.getSu_transportFee()==null?"":vo.getSu_transportFee().toString():"");
            //毛利
            hssfCell = hssfRow.createCell(21);
            hssfCell.setCellValue(isChooseSup?vo.getSu_grossProfit()==null?"":vo.getSu_grossProfit().toString():"");

        }
        for (int a = 0; a <= i; a++) {
            sheet.autoSizeColumn(a);// 設置自動列寬
        }

        // 创建文件输出流，准备输出电子表格
        try {
            String fileName = "应收应付-" + System.currentTimeMillis() + ".xls";
            String agent = request.getHeader("User-Agent");
            boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
            if (isMSIE) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF8");
            } else {
                //兼容火狐，否则中文乱码
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.reset();
//			response.setContentType("application/vnd.ms-excel");
//			response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new WebJsonBean();
    }
}
